package com.yunkeji.utils;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yunkeji.config.properties.RealAuthProperties;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class IdCardAuthUtils {

    private static RealAuthProperties AUTHPROPERTIES = SpringUtil.getBean(RealAuthProperties.class);

    public static Boolean isMatch(String name, String number) {
        HttpResponse execute =
                HttpUtil.createPost(AUTHPROPERTIES.getHost())
                        .form("cardNo", number)
                        .form("realName", name)
                        .header("Authorization", "APPCODE " + AUTHPROPERTIES.getAppcode())
                        .execute();
        String body = execute.body();
        if (execute.getStatus() != 200) {
            log.error("身份验证接口异常,状态码:{},响应体:{}", execute.getStatus(), body);
            return false;
        } else {
            try {
                JSONObject res = JSONUtil.parseObj(body);
                if ("成功".equals(res.getStr("reason"))) {
                    log.info(
                            "身份验证接口成功,验证姓名:{},身份证:{},状态码:{},响应体:{}",
                            name,
                            number,
                            execute.getStatus(),
                            body);
                    return true;
                } else {
                    log.error("身份验证接口异常,状态码:{},响应体:{}", execute.getStatus(), body);
                    return false;
                }
            } catch (Exception e) {
                log.error(
                        "身份验证接口异常,状态码:{},响应体:{},异常信息:{}",
                        execute.getStatus(),
                        body,
                        e.getMessage(),
                        e);
                return false;
            }
        }
    }
}
